from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import desc
from typing import List, Optional
from datetime import datetime
from backend.database import SessionLocal
from backend.models import JobPosting, User, UserType
from backend.schemas import JobPostingCreate, JobPostingResponse, JobPostingUpdate
from . import models, schemas
import logging

# 设置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 保持前缀空字符串
router = APIRouter(prefix="")

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 获取职位列表
@router.get("/api/job-postings", response_model=List[JobPostingResponse])
async def get_job_postings(
    user_id: Optional[int] = Query(None),
    is_open: Optional[bool] = Query(None),
    db: Session = Depends(get_db)
):
    """
    获取职位列表。可以通过user_id筛选特定用户发布的职位，或查看所有公开职位
    """
    logger.info("进入获取职位列表的窗口"),
    logger.info(f"请求获取职位列表: user_id={user_id}, is_open={is_open}")
    try:
        query = db.query(JobPosting)
        
        # 如果指定了用户ID，则仅返回该用户发布的职位
        if user_id is not None:
            query = query.filter(JobPosting.user_id == user_id)
        
        # 筛选职位状态
        if is_open is not None:
            query = query.filter(JobPosting.is_open == is_open)
        
        # 按发布时间降序排序
        jobs = query.order_by(desc(JobPosting.post_date)).all()
        logger.info(f"成功获取职位列表，找到{len(jobs)}个职位")
        return jobs
    except Exception as e:
        logger.error(f"获取职位列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取职位列表失败: {str(e)}")

# 获取职位详情
@router.get("/api/job-postings/{job_id}", response_model=JobPostingResponse)
async def get_job_posting(job_id: int, db: Session = Depends(get_db)):
    """
    获取特定职位的详情
    """
    logger.info("进入获取职位列表的窗口2"),
    logger.info(f"请求获取职位详情: job_id={job_id}")
    job = db.query(JobPosting).filter(JobPosting.job_id == job_id).first()
    if not job:
        logger.warning(f"职位不存在: job_id={job_id}")
        raise HTTPException(status_code=404, detail="职位不存在")
    logger.info(f"成功获取职位详情: job_id={job_id}")
    return job

# 创建新职位
@router.post("/api/job-postings", response_model=JobPostingResponse)
async def create_job_posting(job: JobPostingCreate, db: Session = Depends(get_db)):
    """
    创建新的职位发布
    """
    logger.info(f"请求创建新职位: poster_id={job.poster_id}")
    # 验证发布者存在
    poster = db.query(User).filter(User.user_id == job.poster_id).first()
    if not poster:
        logger.warning(f"发布者不存在: poster_id={job.poster_id}")
        raise HTTPException(status_code=404, detail="发布者不存在")
    
    # 创建新职位
    db_job = JobPosting(
        job_title=job.job_title,
        company_name=job.company_name,
        location=job.location,
        salary_range=job.salary_range,
        job_description=job.job_description,
        requirements=job.requirements,
        post_date=datetime.utcnow(),
        expiration_date=job.expiration_date,
        is_open=True,
        user_id=job.poster_id
    )
    
    db.add(db_job)
    db.commit()
    db.refresh(db_job)
    logger.info(f"成功创建新职位: job_id={db_job.job_id}")
    return db_job

# 更新职位
@router.put("/api/job-postings/{job_id}", response_model=JobPostingResponse)
async def update_job_posting(job_id: int, job_update: JobPostingUpdate, db: Session = Depends(get_db)):
    """
    更新现有职位信息
    """
    # 查找职位
    db_job = db.query(JobPosting).filter(JobPosting.job_id == job_id).first()
    if not db_job:
        raise HTTPException(status_code=404, detail="职位不存在")
    
    # 验证权限 (只有发布者才能更新)
    if db_job.user_id != job_update.poster_id:
        raise HTTPException(status_code=403, detail="无权限修改此职位")
    
    # 更新职位信息
    update_data = job_update.dict(exclude_unset=True)
    
    # 如果存在poster_id字段，则转换为user_id
    if 'poster_id' in update_data:
        update_data['user_id'] = update_data.pop('poster_id')
    
    for key, value in update_data.items():
        setattr(db_job, key, value)
    
    db.commit()
    db.refresh(db_job)
    return db_job

# 删除职位
@router.delete("/api/job-postings/{job_id}")
async def delete_job_posting(job_id: int, user_id: int = Query(...), db: Session = Depends(get_db)):
    """
    删除职位
    """
    # 查找职位
    db_job = db.query(JobPosting).filter(JobPosting.job_id == job_id).first()
    if not db_job:
        raise HTTPException(status_code=404, detail="职位不存在")
    
    # 验证权限 (发布者或管理员才能删除)
    user = db.query(User).filter(User.user_id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    if db_job.user_id != user_id and user.user_type != UserType.admin:
        raise HTTPException(status_code=403, detail="无权限删除此职位")
    
    # 删除职位
    db.delete(db_job)
    db.commit()
    
    return {"message": "职位已删除"} 